package com.boarsoft.boar.config.apollo.listener;

import com.boarsoft.config.core.ConfigFileListener;
import com.boarsoft.config.core.ConfigFileSyncImpl;
import com.boarsoft.config.core.ConfigListener;
import com.ctrip.framework.apollo.ConfigFileChangeListener;
import com.ctrip.framework.apollo.model.ConfigFileChangeEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

public class ApolloConfigFileChangeListener implements ConfigFileChangeListener {
    private static final Logger log = LoggerFactory.getLogger(ApolloConfigFileChangeListener.class);

    @Resource
    private ConfigFileSyncImpl configFileSync;


    @Override
    public void onChange(ConfigFileChangeEvent configFileChangeEvent) {
        String fp= configFileSync.getFileConfigMap().get(configFileChangeEvent.getNamespace());
        try {
            configFileSync.save(fp, configFileChangeEvent.getNewValue().getBytes(StandardCharsets.UTF_8));
            ConfigListener configListener= configFileSync.getConfigListener(configFileChangeEvent.getNamespace());
            if(configListener!=null) {
                configListener.onReady(fp);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}